<?php
error_reporting("E_ALL");ini_set("display_errors", 1);
include("include/function.php");
include("include/OllamaClient.php");
$config = include("config.php");
include("include/".$config['DB_TYPE'].".class.php");
$db = new db;
$db->connect($config['DB_HOST'],$config['DB_USER'],$config['DB_PWD'],$config['DB_NAME'], $config['DB_PCONNECT']);
$is_debug =!empty($_GET['test'])?true: false;
$pagesize = 10;//根据自已服务器情况进行调整
$sql="select id,host,name,model,error from ollama_list where is_delete=0 and status<2 and updatetime<".strtotime('today')." order by updatetime asc limit ".$pagesize;
$list = $db->get_all($sql);if(empty($list))exit('over');
foreach($list as $info){
$startTime = microtime(true);
$ollama = new OllamaClient('http://'.$info['host'].'/api');
if(strpos('a'.$info['error'],'not support chat')>0 || strpos('a'.$info['model'],'embed')>0 || strpos('a'.$info['model'],'Embedding')>0 || strpos('a'.$info['model'],'bge-')>0 || strpos('a'.$info['model'],'all-minilm')>0){
    $response = $ollama->embed(array(
        'model' => $info['model'],
        "input"=> "Does Ollama support embedding models?"
    ));
    if(!empty($response['embeddings'])){
        $response['message']['content']='支持embedding models';unset($response['embeddings']);
    }
}else{
    $history = array(
        array('role' => 'user', 'content' => '你好'),
      //  array('role' => 'assistant', 'content' => '您好！有什么可以帮助您？')
    );
    $response = $ollama->chat(array(
        'model' => $info['model'],
        "messages"=> $history,
        "stream"=> false
    ));
}
$endTime = microtime(true);
$haoshi = ($endTime - $startTime)*1000;
if($is_debug)echo $info['host'].'->'.$info['name'].'<br>耗时：'.$haoshi . 'ms<br>';
if ($response && isset($response['message']['content'])) {
    $content = removeEmojiAndSpecialChars($response['message']['content']);
    if(empty($content))$content=json_encode($response,JSON_UNESCAPED_UNICODE);
    if($is_debug)echo "AI回复:<pre>" . $content;
    $status=1;
    $error=addslashes($content);
}else if(!empty($response['error'])){
    $status=2;
    $error=addslashes($response['error']);
    if($is_debug)echo '不可用：'.$response['error'];
}else{
    if(empty($response))$response='超时了';
    if(is_array($response))$response = json_encode($response,JSON_UNESCAPED_UNICODE);
    if($is_debug)echo '不可用：'.$response;
    $status=2;
    $error=addslashes($response);
}
$update=[];
$update['status']=$status;
$update['error']=$error;
$update['haoshi']=$haoshi;
$update['updatetime']=time();
$sqlarr=[];foreach($update as $k=>$v){$sqlarr[]="`".$k."`='".$v."'";}
$db->query("update ollama_list set ".implode(",",$sqlarr)." where id=".$info['id']);

if($info['id']){
    echo '<br>'.$info['id'];
}else{
    exit('over');
}
}